"""
树
"""

import logging
from collections import defaultdict
from typing import (
    Any,
    Dict,
    List,
    Optional,
    DefaultDict,
)

__all__ = [
    "build_tree",  # -> 构建树形结构
]

logger = logging.getLogger()


def build_tree(
        data: Dict[str, Any],
        data_list: List[dict],
        id_field: str,
        parent_id_field: str,
) -> None:
    """
    构建树形结构

    >>> tree_data = {}
    >>> build_tree(
    >>>     tree_data={},
    >>>     data_list=[
    >>>         {"id": 1, "parent_id": None, "name": "Root"},
    >>>         {"id": 2, "parent_id": 1, "name": "Left Node 1"},
    >>>         {"id": 3, "parent_id": 2, "name": "Left Node 2"},
    >>>         {"id": 4, "parent_id": 2, "name": "Left Node 3"},
    >>>         {"id": 5, "parent_id": 3, "name": "Left Node 4"},
    >>>         {"id": 6, "parent_id": 1, "name": "Right Node 1"},
    >>>     ],
    >>>     id_field="id",
    >>>     parent_id_field="parent_id",
    >>> )
    >>> tree_data
        {
            "id": 1,
            "parent_id": null,
            "name": "Root",
            "children": [
                {
                    "id": 2,
                    "parent_id": 1,
                    "name": "Left Node 1",
                    "children": [
                        {
                            "id": 3,
                            "parent_id": 2,
                            "name": "Left Node 2",
                            "children": [
                                {
                                    "id": 5,
                                    "parent_id": 3,
                                    "name": "Left Node 4",
                                    "children": []
                                }
                            ]
                        },
                        {
                            "id": 4,
                            "parent_id": 2,
                            "name": "Left Node 3",
                            "children": []
                        }
                    ]
                },
                {
                    "id": 6,
                    "parent_id": 1,
                    "name": "Right Node 1",
                    "children": []
                }
            ]
        }

    :param data:            最终返回的数据
    :param data_list:       字典列表
    :param id_field:        ID 字段名
    :param parent_id_field: 父节点 ID 字段名
    :return:                None
    """

    try:
        root: Optional[dict] = None
        obj_children: DefaultDict[Any, list] = defaultdict(list)

        for _data in data_list:
            if root is _data.get(parent_id_field) is None:
                root = _data

            obj_children[_data.get(parent_id_field)].append(_data)

        if root is None:
            return

        def build(
                obj: dict,
                node: Dict[str, Any],
        ) -> None:
            """
            构建

            :param obj:     对象
            :param node:    节点
            :return:        None
            """

            node.update(obj)
            children: List[dict] = []
            node["children"] = children

            for child in obj_children[obj[id_field]]:
                child_node: Dict[str, Any] = {}
                children.append(child_node)
                build(child, child_node)

        build(root, data)

    except Exception as e:
        logger.error(f"【构建树形结构】错误：{e}")
